package com.xiaoyun.xpath.handler.field;

import cn.wanghaomiao.xpath.model.JXDocument;
import com.xiaoyun.xpath.HandlerUtils;
import com.xiaoyun.xpath.handler.annotation.Xpath;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;


public class StringFieldHandler<T> implements FieldHandler<T> {


    protected <T> void stringMethodInvoke(Class<T> clazz, JXDocument jxDocument, T t, String fieldName, String xpathMapping) throws Exception {
        List<Object> list = jxDocument.sel(xpathMapping);
        String str = (String) list.get(0);
        String methodName = HandlerUtils.getMethodName(fieldName);
        Method method = clazz.getDeclaredMethod(methodName, String.class);
        method.setAccessible(true);
        method.invoke(t, str);
    }


    @Override
    public void handlerField(Class<T> clazz, JXDocument jxDocument, T t, Map<String, String> mappingMap, Field field) throws Exception {
        String fieldName = field.getName();
        if (HandlerUtils.isNotNullMap(mappingMap) && mappingMap.get(fieldName) != null) {
            String xpathMapping = mappingMap.get(fieldName);
            stringMethodInvoke(clazz, jxDocument, t, fieldName, xpathMapping);
        } else {
            Xpath xpath = field.getAnnotation(Xpath.class);
            if (xpath != null) {
                String xpathMapping = xpath.pattern();
                stringMethodInvoke(clazz, jxDocument, t, fieldName, xpathMapping);
            }
        }
    }

    @Override
    public String getType() {
        return String.class.getName();
    }


}
